package com.ktg.mes.pro.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktg.common.constant.UserConstants;
import com.ktg.common.core.domain.APIResult;
import com.ktg.common.core.domain.Result;
import com.ktg.common.utils.StringUtils;
import com.ktg.mes.md.domain.MdItem;
import com.ktg.mes.md.service.IMdItemService;
import com.ktg.mes.pro.domain.*;
import com.ktg.mes.pro.service.*;
import com.ktg.mes.rec.domain.RecProcessesExt;
import com.ktg.mes.rec.service.IRecProcessesExtService;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Param;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.core.domain.AjaxResult;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.utils.poi.ExcelUtil;
import com.ktg.common.core.page.TableDataInfo;

/**
 * 工艺组成Controller
 *
 * @author yinjinlu
 * @date 2022-05-13
 */
@RestController
@RequestMapping("/mes/pro/routeprocess")
public class ProRouteProcessController extends BaseController
{
    @Autowired
    private IProRouteProcessService proRouteProcessService;

    @Autowired
    private IProRouteProductService proRouteProductService;

    @Autowired
    private IProProcessService proProcessService;

    @Autowired
    private IMdItemService mdItemService;

    @Autowired
    private IRecProcessesExtService recProcessesExtService;
    @Autowired
    private IProTaskService proTaskService;

    @Autowired
    private IProWorkorderService proWorkorderService;
    @Autowired
    private IProRouteService proRouteService;


    /**
     * 查询工艺组成列表
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:routeprocess:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProRouteProcess proRouteProcess)
    {
        startPage();
        List<ProRouteProcess> list = proRouteProcessService.selectProRouteProcessList(proRouteProcess);
        return getDataTable(list);
    }

    /**
     * 根据查询工艺组成列表的最大排序号，和最大组号
     */
    @GetMapping("/findOrderAndGroup")
    public Result<Map> findOrderAndGroup(ProRouteProcess proRouteProcess,HttpServletRequest req){
        APIResult apiLog = new APIResult("根据查询工艺组成列表的最大排序号，和最大组号",req,proRouteProcess);
        try{
            QueryWrapper<ProRouteProcess> queryWrapper1 = new QueryWrapper<>(proRouteProcess);
            queryWrapper1.orderByDesc("order_num");
            queryWrapper1.last(" limit 0,1");
            ProRouteProcess process1 = proRouteProcessService.getOne(queryWrapper1);
            Integer order = 0;
            if(process1 != null){
                order = process1.getOrderNum();
            }

            QueryWrapper<ProRouteProcess> queryWrapper2 = new QueryWrapper<>(proRouteProcess);
            queryWrapper2.orderByDesc("group_num");
            queryWrapper2.last(" limit 0,1");
            ProRouteProcess process2 = proRouteProcessService.getOne(queryWrapper2);
            Integer group = 0;
            if(process2 != null){
                group = process2.getGroupNum();
            }

            Map<String,Integer> map = new HashMap<>();
            map.put("orderNum",order);
            map.put("groupNum",group);
            return apiLog.ok(map);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }



    /**
     * 查询指定产品的工艺组成
     * @return
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:routeproduct:list')")
    @GetMapping("/listProductProcess/{taskId}")
    public AjaxResult listProductProcess(@PathVariable("taskId") String taskId){
        ProTask proTask = proTaskService.getById(Long.valueOf(taskId));
        MdItem mdItem = mdItemService.getById(proTask.getItemId());
        if (proTask.getViscosity() == null){
            proTask.setViscosity(mdItem.getViscosity());
        }

        if (proTask.getRouteId() == null || proTask.getRouteId() <= 0){
            if (mdItem.getProcessProductName() == null){
                return new  AjaxResult(600,"产品未添加工序分类");
            }

            ProRoute route = proRouteService.findRoute(proTask.getMachineryId(),mdItem.getProcessProductName());
            if (route != null){
                proTask.setRouteId(route.getRouteId());
            }else {
                return new  AjaxResult(601,"请先选择工艺流程");
            }

            proTaskService.updateById(proTask);
        }

        ProRouteProcess param = new ProRouteProcess();
        param.setRouteId(proTask.getRouteId());
        List<ProRouteProcess>  list = proRouteProcessService.selectProRouteProcessList(param);
        return AjaxResult.success(list);
    }


    /**
     * 查询指定产品的工艺组成
     * @return
     */
    @GetMapping("/process")
    public AjaxResult process(@RequestParam("batchNo") String batchNo,@RequestParam("type") String type){
        ProTask proTask = new ProTask();
        proTask.setBatchNo(batchNo);
        QueryWrapper<ProTask> taskQueryWrapper = new QueryWrapper<>(proTask);
        proTask = proTaskService.getOne(taskQueryWrapper);
        if (proTask == null){
            return new  AjaxResult(600,"生产批次不存在");
        }

        MdItem mdItem = mdItemService.getById(proTask.getItemId());
        if (mdItem.getProcessProductName() == null){
            return new  AjaxResult(600,"产品未添加工序分类");
        }
        if (proTask.getViscosity() == null){
            proTask.setViscosity(mdItem.getViscosity());
        }

        ProRouteProduct proRouteProduct = new ProRouteProduct();
        proRouteProduct.setProcessProductName(mdItem.getProcessProductName());
        QueryWrapper<ProRouteProduct> proRouteProductQueryWrapper = new QueryWrapper<>(proRouteProduct);
        ProRouteProduct findRouteProduct = proRouteProductService.getOne(proRouteProductQueryWrapper);
        if (findRouteProduct == null){
            return new  AjaxResult(601,"产品还没有配置工艺");
        }

        //跟新工序信息
        proTask.setRouteId(findRouteProduct.getRouteId());

        proTaskService.updateById(proTask);

        ProRouteProcess param = new ProRouteProcess();
        param.setRouteId(findRouteProduct.getRouteId());
        List<ProRouteProcess>  list = proRouteProcessService.selectProRouteProcessList(param);
        return AjaxResult.success(list);
    }


//    /**
//     * 查询指定产品的工艺组成
//     * @return
//     */
//    @GetMapping("/listFromTask")
//    public AjaxResult listFromTask(@RequestParam(value = "taskId",required = false) String taskId, @RequestParam(value = "processProductName",required = true) String processProductName){
//        ProRouteProduct proRouteProduct = new ProRouteProduct();
//        proRouteProduct.setProcessProductName(processProductName);
//        QueryWrapper<ProRouteProduct> queryWrapper = new QueryWrapper<>(proRouteProduct);
//        queryWrapper.last(" limit 1");
//        ProRouteProduct product = proRouteProductService.getOne(queryWrapper);
//        if(product == null || product.getRouteId() == null){
//            return AjaxResult.error("当前产品未配置工艺路线！");
//        }
//
//        ProRouteProcess param = new ProRouteProcess();
//        param.setRouteId(product.getRouteId());
//        List<ProRouteProcess>  list = proRouteProcessService.selectProRouteProcessList(param);
//
//        return AjaxResult.success(list);
//    }


    /**
     * 导出工艺组成列表
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:routeprocess:export')")
    @Log(title = "工艺组成", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProRouteProcess proRouteProcess)
    {
        List<ProRouteProcess> list = proRouteProcessService.selectProRouteProcessList(proRouteProcess);
        ExcelUtil<ProRouteProcess> util = new ExcelUtil<ProRouteProcess>(ProRouteProcess.class);
        util.exportExcel(response, list, "工艺组成数据");
    }

    /**
     * 获取工艺组成详细信息
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:routeprocess:query')")
    @GetMapping(value = "/{recordId}")
    public AjaxResult getInfo(@PathVariable("recordId") Long recordId)
    {
        return AjaxResult.success(proRouteProcessService.selectProRouteProcessByRecordId(recordId));
    }

    /**
     * 新增工艺组成
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:routeprocess:add')")
    @Log(title = "工艺组成", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProRouteProcess proRouteProcess)
    {
        if(UserConstants.NOT_UNIQUE.equals(proRouteProcessService.checkOrderNumExists(proRouteProcess))){
            return AjaxResult.error("序号已存在！");
        }
        if(UserConstants.NOT_UNIQUE.equals(proRouteProcessService.checkProcessExists(proRouteProcess))){
            return AjaxResult.error("不能重复添加工序！");
        }
        // if(UserConstants.NOT_UNIQUE.equals(proRouteProcessService.checkUpdateFlagUnique(proRouteProcess))){
        //     return AjaxResult.error("当前工艺路线已经指定过关键工序");
        // }
        ProProcess process = proProcessService.selectProProcessByProcessId(proRouteProcess.getProcessId());
        if(StringUtils.isNotNull(process)){
            proRouteProcess.setProcessCode(process.getProcessCode());
            proRouteProcess.setProcessName(process.getProcessName());
        }

        //更新上一个工序的nextProcess
        ProRouteProcess preProcess = proRouteProcessService.findPreProcess(proRouteProcess);
        if(StringUtils.isNotNull(preProcess)){
            preProcess.setNextProcessId(proRouteProcess.getProcessId());
            preProcess.setNextProcessCode(proRouteProcess.getProcessCode());
            preProcess.setNextProcessName(proRouteProcess.getProcessName());
            proRouteProcessService.updateProRouteProcess(preProcess);
        }

        //设置当前工序的nextProcess
        ProRouteProcess nextProcess = proRouteProcessService.findNextProcess(proRouteProcess);
        if(StringUtils.isNotNull(nextProcess)){
            proRouteProcess.setNextProcessId(nextProcess.getProcessId());
            proRouteProcess.setNextProcessCode(nextProcess.getProcessCode());
            proRouteProcess.setNextProcessName(nextProcess.getProcessName());
        }else{
            proRouteProcess.setNextProcessId(0L);
            proRouteProcess.setNextProcessName("无");
        }

        return toAjax(proRouteProcessService.insertProRouteProcess(proRouteProcess));
    }

    /**
     * 修改工艺组成
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:routeprocess:edit')")
    @Log(title = "工艺组成", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProRouteProcess proRouteProcess)
    {
        if(UserConstants.NOT_UNIQUE.equals(proRouteProcessService.checkOrderNumExists(proRouteProcess))){
            return AjaxResult.error("序号已存在！");
        }
        if(UserConstants.NOT_UNIQUE.equals(proRouteProcessService.checkProcessExists(proRouteProcess))){
            return AjaxResult.error("不能重复添加工序！");
        }
        ProProcess process = proProcessService.selectProProcessByProcessId(proRouteProcess.getProcessId());
        proRouteProcess.setProcessCode(process.getProcessCode());
        proRouteProcess.setProcessName(process.getProcessName());

        //更新上一个工序的nextProcess
        ProRouteProcess preProcess = proRouteProcessService.findPreProcess(proRouteProcess);
        if(StringUtils.isNotNull(preProcess)){
            preProcess.setNextProcessId(proRouteProcess.getProcessId());
            preProcess.setNextProcessCode(proRouteProcess.getProcessCode());
            preProcess.setNextProcessName(proRouteProcess.getProcessName());
            proRouteProcessService.updateById(preProcess);
        }

        //设置当前工序的nextProcess
        ProRouteProcess nextProcess = proRouteProcessService.findNextProcess(proRouteProcess);
        if(StringUtils.isNotNull(nextProcess)){
            proRouteProcess.setNextProcessId(nextProcess.getProcessId());
            proRouteProcess.setNextProcessCode(nextProcess.getProcessCode());
            proRouteProcess.setNextProcessName(nextProcess.getProcessName());
        }else{
            proRouteProcess.setNextProcessId(0L);
            proRouteProcess.setNextProcessName("无");
        }

        return toAjax(proRouteProcessService.updateProRouteProcess(proRouteProcess));
    }


    /**
     * 打印流程单
     */
    @GetMapping("/jimureport/{taskId}")
    public JSONObject jimureport(@PathVariable("taskId")String taskId){
        try{
            ProTask proTask = proTaskService.getById(Long.valueOf(taskId));
            ProWorkorder workorder = proWorkorderService.getById(proTask.getWorkorderId());

            List<List<ProRouteProcessData>> processList = new ArrayList<>();


            if (workorder.getParentRouteIdIds() != null){
                String[] routeIds = workorder.getParentRouteIdIds().split(",");
                String[] indexs = workorder.getParentRouteIndexs().split(",");

                for (int i =0;i < routeIds.length;i++){
                    ProTask item = new ProTask();
                    item.setRouteId(Long.valueOf(routeIds[i]));
                    item.setOrderNum(Integer.valueOf(indexs[i]));
                    List<ProRouteProcessData> prList = proRouteProcessService.selectTaskProcessFromTask(item);
                    processList.add(prList);
                }
            }

            proTask.setOrderNum(9999999);
            List<ProRouteProcessData> prList = proRouteProcessService.selectTaskProcessFromTask(proTask);
            processList.add(prList);


            List<Map> list = new ArrayList<>();

            boolean isSplit = processList.size() > 1? true:false; //是否是拆分单
            Integer groupNum = 0;
            Integer lastNum = 0;
            for (int i = 0; i < processList.size(); i++) {
                List<ProRouteProcessData> itemList = processList.get(i);

                int fenShanIndex = 1; //第几次分散
                int yanMoIndex = 1; //第几次研磨
                lastNum = -1;

                for (int j = 0; j < itemList.size(); j++) {
                    ProRouteProcessData item = itemList.get(j);
                    if (lastNum != item.getGroupNum()){
                        lastNum = item.getGroupNum();
                        groupNum++;
                    }
                    item.setGroupNum(groupNum);
                    QueryWrapper<RecProcessesExt> queryWrapper = new QueryWrapper<>();
                    queryWrapper.orderByAsc("order_pda");
                    queryWrapper.eq("process_id",item.getProcessId());
                    List<RecProcessesExt> list1 = recProcessesExtService.list(queryWrapper);

                    ProRouteProcess proRouteProcess = proRouteProcessService.getById(item.getRecordId());
                    Map<String,String> map = item.dealTechnologicalProcessData(list1,proRouteProcess.getRemark(),fenShanIndex,yanMoIndex);
                    list.add(map);
                    fenShanIndex = Integer.valueOf(map.get("分散")).intValue();
                    yanMoIndex = Integer.valueOf(map.get("研磨")).intValue();
                }



            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data",list);
            return jsonObject;
        }catch (Exception e){
            e.printStackTrace();
            ArrayList arrayList = new ArrayList<>();
            Map map = new HashMap<>();
            map.put("row1","error:"+e.getLocalizedMessage());
            map.put("row2","error:"+e.getMessage());
            map.put("row3","error:"+e.toString());
            arrayList.add(map);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data",arrayList);
            return jsonObject;
        }
    }


    /**
     * 删除工艺组成
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:routeprocess:remove')")
    @Log(title = "工艺组成", businessType = BusinessType.DELETE)
	@DeleteMapping("/{recordIds}")
    public AjaxResult remove(@PathVariable Long[] recordIds)
    {
        return toAjax(proRouteProcessService.deleteProRouteProcessByRecordIds(recordIds));
    }
}
